package com.apex.aolonfitdemo.ui;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.apex.aolonfit.AolonFitManager;
import com.apex.aolonfitdemo.R;
import com.apex.aolonfitdemo.databinding.ActivityAlarmBinding;
import com.apex.aolonfitdemo.dialog.WaitingDialog;
import com.apex.aolonfitdemo.utils.SizeTransform;
import com.apex.ax_bluetooth.callback.AttentionCallback;
import com.apex.ax_bluetooth.callback.EditAttentionCallback;
import com.apex.ax_bluetooth.core.EABleManager;
import com.apex.ax_bluetooth.enumeration.EABleConnectState;
import com.apex.ax_bluetooth.enumeration.QueryWatchInfoType;
import com.apex.ax_bluetooth.model.EABleRemindRespond;
import com.apex.ax_bluetooth.model.EABleReminder;
import com.cyber.bridge.module.bean.AlarmEntity;
import com.cyber.bridge.module.listener.OnCyberAlarmListener;
import com.yanzhenjie.recyclerview.OnItemClickListener;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenu;
import com.yanzhenjie.recyclerview.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.yanzhenjie.recyclerview.widget.DefaultItemDecoration;

import java.util.ArrayList;
import java.util.List;


public class AlarmActivity extends AppCompatActivity {

    private WaitingDialog waitingDialog;

    private List<AlarmEntity> itemList;
    AlarmListAdapter alarmListAdapter;
    private int delete = -1;
    ActivityAlarmBinding activityAlarmBinding;
    int maxCount;
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x40) {
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
                alarmListAdapter.notifyDataSetChanged();
                if (itemList.size() > 0) {
                    activityAlarmBinding.submit.setVisibility(View.VISIBLE);
                }
            } else if (msg.what == 0x41) {
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
                Toast.makeText(AlarmActivity.this, getString(R.string.failed_to_get_data), Toast.LENGTH_SHORT).show();
            } else if (msg.what == 0x42) {
                if (delete >= 0) {
                    itemList.remove(delete);
                    alarmListAdapter.notifyItemRemoved(delete);
                    alarmListAdapter.notifyItemRangeChanged(delete, itemList.size());
                }

                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }

            } else if (msg.what == 0x43) {
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
                Toast.makeText(AlarmActivity.this, getString(R.string.modification_failed), Toast.LENGTH_SHORT).show();
            } else if (msg.what == 0x44) {
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
            } else if (msg.what == 0x45) {
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
                itemList.clear();
                delete = -1;
                alarmListAdapter.notifyDataSetChanged();
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityAlarmBinding = ActivityAlarmBinding.inflate(getLayoutInflater());
        setContentView(activityAlarmBinding.getRoot());
        activityAlarmBinding.tool.setNavigationIcon(R.mipmap.exit_page);
        setSupportActionBar(activityAlarmBinding.tool);
        getSupportActionBar().setTitle(null);
        activityAlarmBinding.tool.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(AlarmActivity.this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        activityAlarmBinding.eventList.setLayoutManager(linearLayoutManager);
        itemList = new ArrayList<>();
        activityAlarmBinding.eventList.addItemDecoration(new DefaultItemDecoration(getColor(android.R.color.transparent), getResources().getDisplayMetrics().widthPixels, (int) SizeTransform.dp2px(2, AlarmActivity.this)));
        alarmListAdapter = new AlarmListAdapter();
        activityAlarmBinding.eventList.setSwipeMenuCreator(new SwipeMenuCreator() {
            @Override
            public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int position) {
                int width = getResources().getDimensionPixelSize(R.dimen.d70);
                int height = getResources().getDimensionPixelOffset(R.dimen.d36);
                SwipeMenuItem deleteItem = new SwipeMenuItem(AlarmActivity.this).setBackground(R.color.color_FF2828)
                        .setText(getString(R.string.delete))
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height);
                rightMenu.addMenuItem(deleteItem);
            }
        });
        AolonFitManager.getInstance().setOnAlarmListener(new OnCyberAlarmListener() {
            @Override
            public void queryAlarmList(@Nullable List<AlarmEntity> list) {

                itemList.clear();
                if (list != null) {
                    itemList.addAll(list);
                }
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(0x40);
                }


            }

            @Override
            public void addAlarm(boolean b) {
                Intent intent = new Intent("add.aolonfit.alarmclock");
                intent.putExtra("result", b);
                sendBroadcast(intent);

            }

            @Override
            public void editAlarm(boolean b) {
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(b ? 0x44 : 0x43);
                }
            }

            @Override
            public void deleteAlarm(boolean b) {
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(b ? 0x42 : 0x43);
                }
            }

            @Override
            public void deleteAllAlarm(boolean b) {
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(b ? 0x45 : 0x43);
                }
            }

            @Override
            public void queryAlarmMaxCount(int i) {
                Log.i("alarm", "最大闹钟数：" + i);
                maxCount = i;
            }
        });
        AolonFitManager.getInstance().queryAlarmMaxCount();

        activityAlarmBinding.eventList.setOnItemMenuClickListener(new OnItemMenuClickListener() {
            @Override
            public void onItemClick(SwipeMenuBridge menuBridge, int adapterPosition) {
                menuBridge.closeMenu();
                int direction = menuBridge.getDirection();
                int menuPosition = menuBridge.getPosition();
                if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
                    if (waitingDialog == null) {
                        waitingDialog = new WaitingDialog(AlarmActivity.this);
                    }
                    if (!waitingDialog.isShowing()) {
                        waitingDialog.show();
                    }
                    delete = adapterPosition;
                    AolonFitManager.getInstance().deleteAlarm(itemList.get(delete));
                }
            }
        });
        activityAlarmBinding.eventList.setAdapter(alarmListAdapter);


        activityAlarmBinding.addEvent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(AlarmActivity.this, AddAlarmActivity.class));


            }
        });
        activityAlarmBinding.submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (waitingDialog == null) {
                    waitingDialog = new WaitingDialog(AlarmActivity.this);
                }
                if (!waitingDialog.isShowing()) {
                    waitingDialog.show();
                }
                AolonFitManager.getInstance().deleteAllAlarm();
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        if (waitingDialog == null) {
            waitingDialog = new WaitingDialog(AlarmActivity.this);
        }
        waitingDialog.show();
        AolonFitManager.getInstance().queryAlarmList();
    }

    @Override
    protected void onDestroy() {
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        if (waitingDialog != null) {
            waitingDialog.dismiss();
            waitingDialog = null;
        }
        itemList = null;

        super.onDestroy();
    }

    public class AlarmListAdapter extends RecyclerView.Adapter<AlarmListAdapter.ViewHold> {

        @NonNull
        @Override
        public ViewHold onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(AlarmActivity.this).inflate(R.layout.adapter_alarm_recyclerview, parent, false);
            return new ViewHold(itemView);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHold holder, int position) {
            if (itemList == null || itemList.isEmpty()) {
                return;
            }
            final AlarmEntity alarmEntity = itemList.get(position);
            holder.nameText.setText(getText(R.string.alarm_clock));
            holder.aSwitch.setOnCheckedChangeListener(null);
            String remindTime = getString(R.string.only_once) + ",";
            int[] cycle = alarmEntity.getRepeat();
            if (cycle != null) {
                for (int i = 0; i < cycle.length; i++) {
                    if (cycle[i] == 1) {
                        if (remindTime.contains(getString(R.string.only_once))) {
                            remindTime = " ";
                        }
                        if (i == 0) {
                            remindTime += (getString(R.string.sun) + ",");
                        } else if (i == 1) {
                            remindTime += (getString(R.string.mon) + ",");
                        } else if (i == 2) {
                            remindTime += (getString(R.string.tue) + ",");
                        } else if (i == 3) {
                            remindTime += (getString(R.string.wed) + ",");
                        } else if (i == 4) {
                            remindTime += (getString(R.string.thur) + ",");
                        } else if (i == 5) {
                            remindTime += (getString(R.string.fri) + ",");
                        } else if (i == 6) {
                            remindTime += (getString(R.string.sat) + ",");
                        }
                    }

                }


            }
            if (!TextUtils.isEmpty(remindTime)) {
                remindTime = (remindTime.substring(0, remindTime.length() - 1) + " ");
            }
            int hour = alarmEntity.getHour();
            int minute = alarmEntity.getMinute();
            remindTime += ((hour < 10 ? "0" + hour : hour) + ":" + (minute < 10 ? "0" + minute : minute));
            holder.timeText.setText(remindTime);
            holder.aSwitch.setChecked(alarmEntity.isEnabled());
            holder.aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    int layoutPosition = holder.getLayoutPosition();
                    if (layoutPosition == position) {
                        alarmEntity.setEnabled(isChecked);
                        if (waitingDialog == null) {
                            waitingDialog = new WaitingDialog(AlarmActivity.this);
                        }
                        if (!waitingDialog.isShowing()) {
                            waitingDialog.show();
                        }
                        AolonFitManager.getInstance().editAlarm(alarmEntity);

                    }
                }
            });
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });

        }

        @Override
        public int getItemCount() {
            return itemList == null ? 0 : itemList.size();
        }


        class ViewHold extends RecyclerView.ViewHolder {
            TextView nameText;
            TextView timeText;
            Switch aSwitch;

            public ViewHold(@NonNull View itemView) {
                super(itemView);
                nameText = itemView.findViewById(R.id.event_name);
                timeText = itemView.findViewById(R.id.remind_time);
                aSwitch = itemView.findViewById(R.id.event_switch);

            }
        }

    }

}
